<?php

namespace app\admin\controller;

use app\common\BaseHelper;
use app\admin\model\Product;
use app\admin\model\ProductBatchStock;
use app\admin\model\PurchaseProduct;
use app\admin\model\PurchaseReceiving;
use app\admin\model\PurchaseReceivingCar;
use app\admin\model\PurchaseReceivingProduct;

use think\Db;
use think\Exception;
use think\Request;

class Receiving extends Base
{

    public function index(){
        $sup = \app\admin\model\Supplier::where('status',1)->select();

        $request = $this->request;
        $param = $request->param();
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        if($request->isAjax()){
            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'] + 1;
            // 排序条件
            $order = 'a.create_date DESC';
            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($this->defaultWhere, $where);
            }
            $join = [
                ['purchase b','b.id=a.purchase_id'],
                ['supplier c','c.id=b.supplier_id'],
                ['operator d','d.id=a.person']
            ];
            $field = 'a.*,c.name,d.login_name';
            $data = model('purchase_receiving')->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->order($order)->select();
            $count = model('purchase_receiving')->alias('a')->where($where)->join($join)->field($field)->count();
            $result = [
                'code' => '0',
                'msg' => '',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }

        return $this->fetch($this->indexView,[
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param(),
            'sup' => $sup
        ]);
    }

    public function add(Request $request){
        $param = $request->param();

        if($this->check_params($param)){
            $res = PurchaseProduct::where('purchase_id',$param['purchase_id'])->select();
            $listarr = [];
            foreach ($res as $v){
                array_push($listarr,[
                    'purchase_id' => $v['purchase_id'],
                    'product_id' => $v['product_id'],
                    'product_name' => $v['product_name'],
                    'bar_code' => $v['bar_code'],
                    'spec' => $v['spec'],
                    'pu_stock' => $v['pu_stock'],
                    'purchase_price' => $v['purchase_price'],
                    'unit' => $v['unit'],
                    'shou_price' => $v['purchase_price']
                ]);
            }
            $PurchaseReceivingCar = PurchaseReceivingCar::where('purchase_id',$param['purchase_id'])->find();
            if(!$PurchaseReceivingCar){
                $model = new PurchaseReceivingCar();
                $model->saveAll($listarr,false);
            }
        }else{
            return $this->error('参数异常');
        }

        $supplierName = \app\admin\model\Supplier::getSupplierName($param['supid']);
        return $this->fetch('',[
            'supname' => $supplierName,
            'supid' => $param['supid'],
            'purchase_id' => $param['purchase_id']
        ]);
    }

    //收货单详情
    public function detail(Request $request){
        $param = $request->param();
        if(empty($param['id'])){
            return $this->error('参数错误');
        }
        $PurchaseReceiving = PurchaseReceiving::where('id',$param['id'])->find();
        $Purchase = \app\admin\model\Purchase::where('id',$PurchaseReceiving->purchase_id)->find();
        if($request->isAjax()){
            $res = PurchaseReceivingProduct::where('receiving_id',$param['id'])->order('product_id asc')->select();
            $PurchaseProduct = PurchaseProduct::where('purchase_id',$PurchaseReceiving->purchase_id)->select();
            foreach ($res as &$v){
                foreach ($PurchaseProduct as $value){
                    if($v['product_id'] == $value['product_id']){
                        $v['bar_code'] = $value['bar_code'];
                        $v['product_name'] = $value['product_name'];
                        $v['pu_stock'] = $value['pu_stock'];
                        $v['unit'] = $value['unit'];
                        $v['spec'] = $value['spec'];
                    }
                }
                $v['toal'] = sprintf("%.2f",$v['purchase_price'] * $v['shou_num']/100);
            }
            $result = [
                'code' => '0',
                'msg' => '',
                'data' => $res
            ];
            //dump($result);
            return json($result);
        }else{
            $username = \app\admin\model\Operator::where('id',$PurchaseReceiving->person)->value('login_name');
            $supname = \app\admin\model\Supplier::where('id',$Purchase->supplier_id)->value('name');
            $data['ReceivingId'] = $param['id'];
            $data['PurchaseId'] = $PurchaseReceiving->purchase_id;
            $data['create_user'] = $username;
            $data['supname'] = $supname;
            $data['remarks'] = $PurchaseReceiving->remarks;
            $data['create_date'] = $PurchaseReceiving->create_date;
            return $this->fetch('',[
                'info' => $data
            ]);
        }
    }

    //修改收货单
    public function edit_receiving_car(Request $request){
        $param = $request->param();
        if(empty($param['id']) || empty($param['value'])){
            return $this->error('参数错误');
        }
        $data = PurchaseReceivingCar::get($param['id']);
        $res = PurchaseReceivingCar::where(['purchase_id'=>$param['purchase_id'],'product_id'=>$param['product_id']])->select();
        if($data){
            $othershou_count = 0;
            foreach ($res as $v){
                if($data['id'] != $v['id']){
                    $othershou_count += $v['actual_num'];
                }
            }
            if(($othershou_count + $param['value']) <= $data->pu_stock){
                $data->actual_num = $param['value'];
                $shou_price = $data->purchase_price * $param['value'];
                $data->shou_price = $shou_price;
                if($data->save()){
                    return $this->success('ok');
                }else{
                    return $this->error('操作失败');
                }
            }else{
                return $this->error('收货数量应该小于等于采购数量');
            }

        }else{
            return $this->error('数据异常');
        }
    }

    public function edit_receiving_date(Request $request){
        $param = $request->param();
        if(empty($param['id']) || empty($param['value']) || empty($param['purchase_id']) || empty($param['product_id'])){
            return $this->error('参数错误');
        }
        try{
            $datas = PurchaseReceivingCar::where('purchase_id',$param['purchase_id'])->select();
            foreach ($datas as $v){
                if($v['product_id'] == $param['product_id'] && $v['production_time'] == $param['value']){
                    return $this->error('此生产日期已经存在，不要重复添加');
                }
            }
            $res = PurchaseReceivingCar::get($param['id']);
            if($res){
                $res->production_time = $param['value'];
                $res->save();
                return $this->success('ok');

            }else{
                return $this->error('数据异常');
            }
        }catch (Exception $ex){
            return $this->error($ex->getMessage());
        }
    }

    //添加商品批次（生产日期）
    public function add_rece(Request $request){
        $param = $request->param();
        $res = PurchaseReceivingCar::where(['purchase_id'=>$param['data']['purchase_id'],'product_id'=>$param['data']['product_id']])->select();
        $count = count($res);
        $shou_count = 0;
        foreach ($res as $v){
            $shou_count += $v['actual_num'];
        }
        if($count < $param['data']['pu_stock'] && $shou_count < $param['data']['pu_stock']){
            $model = new PurchaseReceivingCar();
            $model->purchase_id = $param['data']['purchase_id'];
            $model->product_id = $param['data']['product_id'];
            $model->product_name = $param['data']['product_name'];
            $model->bar_code = $param['data']['bar_code'];
            $model->spec = $param['data']['spec'];
            $model->unit = $param['data']['unit'];
            $model->purchase_price = $param['data']['purchase_price'];
            $model->pu_stock = $param['data']['pu_stock'];
            $model->shou_price = $param['data']['purchase_price'];
            if($model->save()){
                $this->success('ok');
            }else{
                $this->error('操作失败');
            }
        }else{
            $this->error('不能再添加，此商品的采购数量是'.$param['data']['pu_stock']);
        }
    }

    //删除收货单某商品
    public function del(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id'])){
                return $this->error('参数不合法');
            }
            $res = PurchaseReceivingCar::get($param['id']);
            if($res){
                if($res->delete()){
                    return $this->success('操作成功');
                }else{
                    return $this->error('操作失败');
                }
            }else{
                return $this->error('数据异常');
            }
        }else{
            return $this->error('非法请求');
        }
    }

    //确认收货
    public function save_receiving(Request $request){
        $createuserid = session('ADMIN')['id'];
        if($request->isPost()){
            $param = $request->param();
            $data = json_decode($param['data'],true);
            $stock = $param['dest'];
            $all_price = 0;
            $all_num = 0;
            foreach ($data as $v){
                $all_num += $v['actual_num'];
                $all_price += $v['actual_num'] * $v['purchase_price'];
            }
            Db::startTrans();
            try{
                $model = new PurchaseReceiving();
                $reid = BaseHelper::getUUID();
                $model->id = $reid;
                $model->purchase_id = $data[0]['purchase_id'];
                $model->receiving_num = $all_num;
                $model->total_price = $all_price;
                $model->person = $createuserid;
                if($param['remarks']){
                    $model->remarks =  $param['remarks'];
                }
                $model->save();
                $listarr = [];
                foreach ($data as $val){
                    $id = BaseHelper::getUUID();

                    array_push($listarr,[
                        'id' => $id,
                        'receiving_id' => $reid,
                        'product_id' => $val['product_id'],
                        'production_time' => $val['production_time'],
                        'shou_num' => $val['actual_num'],
                        'purchase_price' => $val['purchase_price']
                    ]);
                }
                $stockarr = [];
                foreach ($stock as $v){
                    $id = BaseHelper::getUUID();
                    $Stock = \app\admin\model\Stock::where('product_id',$v['product_id'])->find();
                    if(!$Stock){
                        array_push($stockarr,[
                            'id' => $id,
                            'product_id' => $v['product_id'],
                            'marketable' => $v['all_shou'],
                        ]);
                    }else{
                        $Stock->setInc('marketable',$v['all_shou']);
                    }
                    $batcharr = [];
                    foreach ($v['data'] as $val){
                        $res = ProductBatchStock::where(['product_id'=>$val['product_id'],'production_time'=>$val['production_time']])->find();
                        if($res){
                            $res->setInc('num',$val['actual_num']);
                        }else{
                            // 保质期
                            $qualityTtime = Product::where('id', $val['product_id'])->value('quality_time');
                            $deadline = date('Y-m-d', (strtotime($val['production_time']) + 3600*24*$qualityTtime)); // 过期时间
                            array_push($batcharr,[
                                'product_id' => $val['product_id'],
                                'product_name' => $val['product_name'],
                                'production_time' => $val['production_time'],
                                'num' => $val['actual_num'],
                                'deadline' => $deadline
                            ]);
                        }
                    }
                    if($batcharr){
                        $batch = new ProductBatchStock();
                        $batch->saveAll($batcharr,false);
                    }
                }
                if($stockarr){
                    $Stock = new \app\admin\model\Stock();
                    $Stock->saveAll($stockarr,false);
                }
                $model = new PurchaseReceivingProduct();
                //采购单状态改为已经进货
                $Purchase = \app\admin\model\Purchase::get($data[0]['purchase_id']);
                if($Purchase && $Purchase->status == 1){
                    $Purchase->status = 2;
                    $Purchase->save();
                }else{
                    return $this->error('采购单状态异常，操作失败');
                }
                //为商品添加库存
                $model->saveAll($listarr,false);
                //删除中间表数据
                PurchaseReceivingCar::where('purchase_id',$data[0]['purchase_id'])->delete();
                Db::commit();
                return $this->success('ok','/admin/receiving/index');
            }catch (Exception $ex){
                Db::rollback();
                return $this->error($ex->getMessage());
            }
        }else{
            return $this->error('非法请求');
        }
    }

    public function getpurchase_receiving(Request $request){
        $param = $request->param();
        $res = PurchaseReceivingCar::where('purchase_id',$param['purchase_id'])->order('product_id')->select();
        $result = [
            'code' => '0',
            'msg' => '',
            'data' => $res
        ];
        return json($result);
    }

    public function getpurchase(Request $request){
        $param = $request->param();
        $Purchase = \app\admin\model\Purchase::where(['supplier_id'=>$param['supid'],'status'=>1])->order('create_date ASC')->select();

        if($Purchase){
            return json($Purchase);
        }
    }

    private function check_params($param){
        $Purchase = \app\admin\model\Purchase::where(['id'=>$param['purchase_id'],'status'=>1])->find();
        if($Purchase){
            return true;
        }
        return false;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['id']) && $param['id']){
            $where['a.id'] = ['like', '%'.$param['id'].'%'];
        }

        return $where;
    }
}